package com.uinnova.product.eam.base.feign;

import com.alibaba.fastjson.JSONObject;
import com.binary.framework.web.RemoteResult;
import com.uinnova.product.eam.base.feign.exception.FeignEamServerException;
import feign.Response;
import feign.codec.ErrorDecoder;
import org.apache.commons.io.IOUtils;

public class FeignErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        if (response.body() != null) {
            try {
                String body = IOUtils.toString(response.body().asInputStream(), "UTF-8");
                RemoteResult remoteResult = JSONObject.parseObject(body, RemoteResult.class);
                if (remoteResult != null) { return new FeignEamServerException(remoteResult.getMessage()); }
            } catch (Exception e) {
                return e;
            }
        }
        return new FeignEamServerException(methodKey);
    }
}
